<?php include "session.inc.php"; ?>
<?php require_once("../common/config.inc.php");?>
<?php include("../common/db.inc.php"); ?>
<?php
global $currentUser,$divDisplayStyle,$operateResult,$currentDate;

	init();		
	
	function init(){
		$GLOBALS[divDisplayStyle]=array();
		$operation=$_POST["operation"];
		//handle post request - modify user 
		if($operation && $operation=="CreateUser"){
			$GLOBALS[divDisplayStyle]["operateDiv"]="display:none";			
			$GLOBALS[divDisplayStyle]["operateResultDiv"]="display:inline";
			//echo "execute create user...<br/>";
			$GLOBALS[currentUser]=createUser();
			$GLOBALS[operateResult]="Create user succeed!";
		}else{
			$GLOBALS[divDisplayStyle]["operateDiv"]="display:inline";
			$GLOBALS[divDisplayStyle]["operateResultDiv"]="display:none";	
		}	

	}
	
	function getUserId(){
		$userid=null;
		//$sql = "SELECT * FROM medcdb.t_user order by userid desc limit 2";
		/*
		$monthStr=date("m");
		$yearStr=date("y");		
		$sql = "SELECT * FROM medcdb.t_user where userid like '$yearStr.$monthStr%' order by userid desc";
		$connection=getMEDCConnection();
		$userArray=executeQuery($sql,$connection);	
		
		if(count($userArray)<2){
			$userid=$yearStr.$monthStr."000001";
		}else{
			$userid=$userArray[1]["userid"];
		}
		*/
		$t=time(); 		
		$userid=date("ymdHis",$t++);//11 03 15 01 52 41 - 11 02 00 00 01
		$connection=getMEDCConnection();
		$userArray=array();
		$loopCount=0;

		//echo "try user id - ".$userid."<br/>";
		$sql = "SELECT * FROM medcdb.t_user where userid='$userid'";				
		$userArray=executeQuery($sql,$connection);	
		
		while(count($userArray)>0 && $loopCount<100){	
			$userid=date("ymdHis",$t++); //110315092512
			//echo "try user id - ".$userid."<br/>";
			$sql = "SELECT * FROM medcdb.t_user where userid='$userid'";				
			$userArray=executeQuery($sql,$connection);	
			$loopCount++;
		}
	
		return $userid;
	}
	
	function createUser(){
		//$columnNames=array("userid","usertype","valto","contactinfo","comment","createdate");
		$userid=getUserId();
		$password=$_POST["password"];
		$usertype=$_POST["usertype"];
		$valfrom=$_POST["valfrom"];
		$valto=$_POST["valto"];
		$contactinfo=$_POST["contactinfo"];
		$comment=$_POST["comment"];
		$createdate=date("Y-m-d H:i:s");//yyyy-MM-dd,2006-07-11 09:32:12		
		$password=md5($password);
		
		$sql = "insert into medcdb.t_user (userid,password,usertype,valfrom,valto,contactinfo,comment,createdate)" .
				"values('$userid','$password','$usertype','$valfrom','$valto','$contactinfo','$comment','$createdate')";
		//echo "createUser sql is :".$sql;			
		$connection=getMEDCConnection();
		//echo("sql is:".$sql);	
		executeUpdate($sql,$connection);
		//return the created user
		$sql = "SELECT * FROM medcdb.t_user where userid='$userid'";				
		$userArray=executeQuery($sql,$connection);	
		$userArray[0]["password"]=$_POST["password"];	
		return $userArray[0];
	}		
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="keywords" content="" />
<meta name="Description" content="" />
<meta name="author" content="" />
<title>User Create Page</title>
<link rel="stylesheet" type="text/css" href="../css/medc.css" />
<script language="JavaScript" type="text/javaScript" src="../js/medc_common.js"></script>
<script language="JavaScript" type="text/javaScript" src="../js/CalendarPopup.js"></script>
<script language="JavaScript" type="text/javascript">	
	var ValidateFromDateCalendar=null;
	var ValidateToDateCalendar=null;
	
	function init(){
	    //set the scheduleTabCalendar
	    ValidateToDateCalendar = new CalendarPopup("ValidateToDateCalendarDiv");
	    ValidateToDateCalendar.setCssPrefix("TEST");
	    ValidateToDateCalendar.setReturnFunction("calendarReturnFunction");
	    
	    ValidateFromDateCalendar = new CalendarPopup("ValidateFromDateCalendarDiv");
	    ValidateFromDateCalendar.setCssPrefix("TEST");
	    ValidateFromDateCalendar.setReturnFunction("calendarReturnFunction");	    
	}
		
	function calendarReturnFunction(y, m, d) {
	    if (window.CP_targetInput != null) {
	        var dt = new Date(y, m - 1, d, 0, 0, 0);
	        if (window.CP_calendarObject != null) {
	            window.CP_calendarObject.copyMonthNamesToWindow();
	        }
	        window.CP_targetInput.value = formatDate(dt, window.CP_dateFormat);
	    } else {
	        alert('Use setReturnFunction() to define which function will get the clicked results!');
	    }
	}
		
	function clickCalendar(calendarName){
		var inputName=null;
		var anchorName=null;
		var calendarObj=null;
		if(calendarName=="ValidateToDateCalendar"){
			inputName="valto";
			anchorName="ValidateToDateCalendarImg";
			calendarObj=ValidateToDateCalendar;			
		}else if(calendarName=="ValidateFromDateCalendar"){
			inputName="valfrom";
			anchorName="ValidateFromDateCalendarImg";
			calendarObj=ValidateFromDateCalendar;					
		}
		var inputObj=document.getElementById(inputName);
		calendarObj.select(inputObj,anchorName,'yyyy-MM-dd');	
		return false;	
	}	
	
	function doPost(operationName){
		if(validate()==false){
			return;
		}
		if(operationName=="saveUser"){
		    var isConfirm = window.confirm("Are you sure to save changes?");
		    if (isConfirm == false) {
		        return;
		    }				
		}
		document.getElementById("operation").value="CreateUser";
		//document.forms["medcform"].attributes["action"]="UserCreate.php";
		document.forms["medcform"].submit();
	}
	
	function validate(){
		
		//check password		
		var password=document.getElementById("password").value;
		if(isWhitespace(password)){
			alert("password can not be empty!");		
			return false;				
		}else if(password.length>8 || password.length<4){
			alert("password length is 4-8!")			
			return false;
		}else if(isNumAndAlpha(password,"password")==false){				
			alert("password should only contain numbers and alphabets!");			
			return false;
		}
		
		//check Validate Date
		var validateToDate=document.getElementById("valto").value;
		if(isWhitespace(validateToDate)){
			alert("validate to date can not be empty!");		
			return false;				
		}
		var validateFromDate=document.getElementById("valfrom").value;
		if(isWhitespace(validateFromDate)){
			alert("validate from date can not be empty!");		
			return false;				
		}		
		return true;
	}
</script>
</head>
<body onload="init()">
	<!--Top area-->
	<div id="toparea">
		<?php include "../common/header.inc.php"?>
	</div>
	<div id="menu">
		<?php include "AdminMenu.inc.php";?>
	</div>	

	<!--Main area-->
	<div id="mainarea">
		<form method="post" action="UserCreate.php" name="medcform">
		<input type="hidden" name="operation" id="operation" />
		<div id="operateDiv" style="<? echo $GLOBALS[divDisplayStyle]["operateDiv"] ?>" >
			<table>
				<tr style="display:none">
					<td align="left"><label for="userid">User Id</label></td>
					<td align="left"><input type="text" name="userid" id="userid" maxLength="30" size="20" readonly="true" /><td>
				</tr>
				<tr>
					<td align="left" style="width:120px;"><label for="usertype">User Type</label></td>
					<td align="left">
					<select name="usertype" id="usertype">
					<?
					$userTypes=array('Normal' => '2', 'Admin' => '1');
					$checked="";
					foreach ($userTypes as $key => $value) {	    		    
						if($value==2){
							$checked="selected";
						}else{
							$checked="";
						}
					?>
					<option value="<? echo $value ?>" <? echo $checked ?> ><? echo $key ?> </option>
					<?}?>

					</select>
					<td>
				</tr>	
				<tr>
					<td align="left" valign="bottom"><label for="password">Password</label></td>
					<td align="left">			
						<input type="text" name="password" id="password" maxLength="10" size="20" />			
						<label for="password" >(4-8 numbers and alphabets)</label>
					<td>
				</tr>
				<tr>
					<td align="left"><label for="valfrom">ValFrom Date</label></td>
					<td nowrap="true"align="left">		
						<div id="ValidateFromDateDiv"><input name="valfrom" id="valfrom" type="text" title="Validate From Date" value="<? echo $GLOBALS[currentUser]['valfrom']?>"/>  
							<div id="ValidateFromDateCalendarDiv" style="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></div>
							<img src="../images/icon-select-date.gif" alt="select date icon" name="ValidateFromDateCalendarImg" id="ValidateFromDateCalendarImg" height="14" width="13"
							onclick="clickCalendar('ValidateFromDateCalendar')" />
						</div>		
					</td>
				</tr>					
				<tr>
					<td align="left"><label for="valto">ValTo Date</label></td>
					<td nowrap="true"align="left">		
						<div id="ValidateToDateDiv"><input name="valto" id="valto" type="text" title="Validate To Date" value="<? echo $GLOBALS[currentUser]['valto']?>"/>  
							<div id="ValidateToDateCalendarDiv" style="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></div>
							<img src="../images/icon-select-date.gif" alt="select date icon" name="ValidateToDateCalendarImg" id="ValidateToDateCalendarImg" height="14" width="13"
							onclick="clickCalendar('ValidateToDateCalendar')" />
						</div>		
					</td>
				</tr>		
				<tr>
					<td align="left" valign="top" ><label for="contactinfo">Contact</label></td>
					<td align="left"><textarea id="contactinfo" name="contactinfo" rows="3" ></textarea><td>
				</tr>	
				<tr>
					<td align="left" valign="top" ><label for="comment">Comment</label></td>
					<td align="left"><textarea id="comment" name="comment" rows="3" ></textarea><td>
				</tr>		
				<tr style="display:none">
					<td align="left"><label for="createdate">Create Date</label></td>
					<td align="left"><input type="text" name="createdate" id="createdate" maxLength="30" size="20" readonly="true" value="<? echo $GLOBALS[currentUser]['createdate']?>"/><td>
				</tr>	
				<tr>
					<td>&nbsp;</td>
					<td>
						<div align="right">
							<input type="button" name="AddUser" value="Save" id="AddUser" onclick="doPost('addUser')" />
						</div>	
					</td>
				</tr>
			</table>
		</div>	
		</form>
		<div id="operateResultDiv" style="<? echo $GLOBALS[divDisplayStyle]["operateResultDiv"] ?>" >
			<div align="left">
				<p><?php echo $GLOBALS[operateResult]; ?></p>
				 <table>
				<tr>
					<td align="left"><label for="created_userid">User Id</label></td>
					<td align="left"><span id="created_userid"><? echo $GLOBALS[currentUser]['userid']?></span><td>
				</tr>
				<tr>
					<td align="left"><label for="created_usertype">User Type</label></td>
					<td align="left"><span id="created_usertype"><? echo $GLOBALS[currentUser]['usertype']?></span><td>
				</tr>	
				<tr>
					<td align="left"><label for="created_password">Password</label></td>
					<td align="left"><span id="created_password"><? echo $GLOBALS[currentUser]['password']?></span><td>
				</tr>
				<tr>
					<td align="left"><label for="created_valfrom">ValFrom Date</label></td>
					<td align="left"><span id="created_valfrom"><? echo $GLOBALS[currentUser]['valfrom']?></span><td>
				</tr>	
				<tr>
					<td align="left"><label for="created_valto">ValTo Date</label></td>
					<td align="left"><span id="created_valto"><? echo $GLOBALS[currentUser]['valto']?></span><td>
				</tr>
				<tr>
					<td align="left" valign="top" ><label for="created_contactinfo">Contact</label></td>
					<td align="left"><textarea id="created_contactinfo" name="created_contactinfo" rows="3" readonly="true"><? echo $GLOBALS[currentUser]['contactinfo']?></textarea><td>
				</tr>	
				<tr>
					<td align="left" valign="top" ><label for="created_comment">Comment</label></td>
					<td align="left"><textarea id="created_comment" name="created_comment" rows="3" readonly="true"><? echo $GLOBALS[currentUser]['comment']?></textarea><td>
				</tr>		
				<tr>
					<td align="left"><label for="created_createdate">Create Date</label></td>
					<td align="left"><span name="created_createdate" id="created_createdate"><? echo $GLOBALS[currentUser]['createdate']?></span><td>
				</tr>								
			</div>
		</div>			
	</div>
</body>
</html>
